package com.atguigu.java.test1;

import org.junit.Test;

import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 实现TCP的网络编程
 * 例题二：客户端发送文件给服务端，服务端将文件保存在本地
 *
 * @author shkstart
 * @create 2021-02-01 19:59
 */
public class TCPTest2 {
    @Test
    //客户端
    public void client() {
        Socket s1 = null;
        FileInputStream fo = null;
        OutputStream op = null;
        try {
            //创建Socket对象 连接服务器端的IP和 端口号
            InetAddress i1 = InetAddress.getByName("127.0.0.1");
            s1 = new Socket(i1, 1221);

            fo = new FileInputStream("Capture001.png");
            op = s1.getOutputStream();

            byte[] bytes = new byte[1024];
            int len;
            while ((len = fo.read(bytes)) != -1) {
                op.write(bytes, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (op != null)
                    op.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (fo != null)
                    fo.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (s1 != null)
                    s1.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


    }

    //服务器端
    @Test
    public void server() {
        ServerSocket s1 = null;
        Socket accept = null;
        InputStream i2 = null;
        FileOutputStream f1 = null;
        try {
            //创建ServerSocket对象 和端口号

            s1 = new ServerSocket(1221);
            accept = s1.accept();

            //创建输入输出流
            i2 = accept.getInputStream();

            f1 = new FileOutputStream("local.png");

            byte[] bytes = new byte[1024];
            int len;
            while ((len = i2.read(bytes)) != -1) {

                f1.write(bytes, 0, len);

            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (f1 != null)
                    //关闭资源
                    f1.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (i2 != null)
                    i2.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (accept != null)
                    accept.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (s1 != null)
                    s1.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


    }
}
